const mysql = require('mysql2/promise');
const {connection} = require('./common');

//获取所有数据
async function selectUsers(){
    let sql = 'select * from user';
    let res = await connection.execute(sql);
    return JSON.stringify(res[0]);
}

//新建数据
async function addUsers(data){
    let obj = data;
    let str = '';
    let arr = []
    for(let i in obj){
        if(i == 'upload'){
        arr.push('UserImg')
        str = str + `'${obj[i][0].response.addr}',`
        }else{
            arr.push(i)
            str = str + `'${obj[i]}',`
             }
        }
    let x = str.slice(0,str.length-1);
    let sql = `INSERT INTO user(${arr}) VALUES(${x}) `
    await connection.execute(sql)
    return JSON.stringify("success");

}

//删除的操作
async function deleteUsers(data){
    let obj = data;
    let Userwxno = obj.Userwxno;
    let sql = `DELETE FROM user WHERE Userwxno = '${Userwxno}'`
    await connection.execute(sql)
    return JSON.stringify("success");
}

//修改的操作
async function putUsers(data){
    let result = data;
    let newObj = result.new;
    let id = result.old.Userwxno;
    let str = '';
    for(let i in newObj){
      str = str + `${i} = '${newObj[i]}',`
    }
    let x = str.slice(0,str.length-1);
    let sql = `UPDATE user SET ${x} WHERE Userwxno = '${id}'`
    let res = await connection.execute(sql)
    return JSON.stringify('success!')
}
module.exports={
    selectUsers,
    addUsers,
    deleteUsers,
    putUsers
}